package markdown;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * HttpClient请求工具类
 */
public class HttpClientUtil {

    // 缓存大小
    public static final int cache = 10 * 1024;
    CloseableHttpClient httpClient = null;

    // 配置
    private static RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(15000) // 返回等待时间
            .setConnectTimeout(15000) // 连接超时
            .setConnectionRequestTimeout(15000)
            .build();

    public HttpClientUtil() {
        this.httpClient = HttpClients.createDefault();
    }

    public CloseableHttpClient getHttpClient() {
        return httpClient;
    }

    /**
     * 发送get请求
     *
     * @param httpUrl   请求地址
     * @param paramMap  参数，url后面
     * @param headerMap 请求头
     */
    public String sendHttpGet(String httpUrl, Map<String, String> paramMap, Map<String, String> headerMap) {
        // 创建get请求
        HttpGet httpGet = null;
        if (paramMap != null && paramMap.size() > 0) {
            // 封装请求参数
            List<BasicNameValuePair> list = new ArrayList<>();
            for (String key : paramMap.keySet()) {
                list.add(new BasicNameValuePair(key, paramMap.get(key)));
            }
            // 转化参数
            String params = null;
            try {
                params = EntityUtils.toString(new UrlEncodedFormEntity(list, Consts.UTF_8));
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(params);
            if (params != null) {
                httpUrl = httpUrl + "?" + params;
            }
        }
        httpGet = new HttpGet(httpUrl);
        // 设置请求头
        if (headerMap != null && headerMap.size() > 0) {
            for (String key : headerMap.keySet()) {
                httpGet.addHeader(key, headerMap.get(key));
            }
        }
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            httpGet.setConfig(requestConfig);
            // 执行请求
            response = httpClient.execute(httpGet);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接,释放资源
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

    /**
     * 发送form-data格式的post请求，可以上传附件
     *
     * @param httpUrl  地址
     * @param paramMap 参数，body里面
     * @param headerMap 请求头
     * @param files    附件
     */
    public String sendHttpPostAndFile(String httpUrl, Map<String, String> paramMap, Map<String, String> headerMap, List<File> files) {
        // 创建httpPost
        HttpPost httpPost = new HttpPost(httpUrl);
        httpPost.setConfig(requestConfig);
        // 设置参数 编码
        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
        MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
        for (String key : paramMap.keySet()) {
            meBuilder.addPart(key, new StringBody(paramMap.get(key), contentType));
        }
        // 设置请求头
        if (paramMap != null && paramMap.size() > 0) {
            for (String key : headerMap.keySet()) {
                httpPost.addHeader(key, headerMap.get(key));
            }
        }
        // 附件
        if (files != null && files.size() > 0) {
            // 单附件或多附件
            String fileKey = files.size() > 1 ? "files" : "file";
            for (File file : files) {
                FileBody fileBody = new FileBody(file);
                meBuilder.addPart(fileKey, fileBody);
            }
        }
        // 创建HttpEntity
        HttpEntity reqEntity = meBuilder.build();
        httpPost.setEntity(reqEntity);

        return sendHttpPost(httpPost);
    }

    /**
     * 发送Post请求
     */
    private String sendHttpPost(HttpPost httpPost) {
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            // 执行请求
            response = httpClient.execute(httpPost);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接,释放资源
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

}

